package sdkaibaidu

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
)

// TextToSpeech Voice Composition
func TextToSpeech(msg string, path string) int {
	APIKEY := "qKfKR0RPVGGnxpL8BTUQ39nc"
	APISECRET := "x1Aq5is0OilkZHilTVdAvxWAUjvGo9rG"
	fmt.Println(path)
	client := NewVoiceClient(APIKEY, APISECRET)

	file, err := client.TextToSpeech(msg)
	if err != nil {
		log.Fatal(err)
		return -1
	}

	f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
		return -1
	}
	defer f.Close()
	if _, err := f.Write(file); err != nil {
		log.Fatal(err)
		return -1
	}
	return 0
}

//TextToVoice tools
func TextToVoice(input string, output string) int {

	fmt.Println(input, output)
	msg := ToolsReadTxtMsg(input)
	if len(msg) == 0 {
		fmt.Println("超过60秒，减少子数810")
		return -1
	}
	if len(msg) >= 780 {
		fmt.Println("超过60秒，减少子数810")
		return -1
	} else {
		fmt.Println(input, "==========", len(msg))
	}
	return TextToSpeech(msg, output)
}

//ToolsReadTxtMsg 读取文本数据
func ToolsReadTxtMsg(path string) string {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer file.Close()

	var buffer []string
	scanner := bufio.NewScanner(file)
	var lines string

	for scanner.Scan() {
		lines = scanner.Text()
		if strings.Contains(lines, "---") == true {
			fmt.Println("-----------")
			break
		}
		buffer = append(buffer, lines)

	}
	if len(buffer) == 0 {
		return ""
	}

	//字符串拼接
	var result string
	for _, data := range buffer {
		result += data
		result += "\r\n"
	}
	fmt.Println(result)
	return result

}
